<?php

namespace app\command;

use app\helper\Schema;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;

class SchemaSourceCommand extends Command {

    use \app\helper\SqlTraits;

    public function configure() {
        $this->setName('schema:source')->setDescription('导入一个sql文件到数据库')
                ->addArgument('file', InputArgument::REQUIRED, '需要导入的sql文件,例：app_invited.sql(支持相对路径和绝对路径)');
    }

    public function execute(InputInterface $input, OutputInterface $output) {
        $file = $input->getArgument('file');
        if (!($filepath = static::searchFile($file))) {
            $output->writeln('<error>SQL文件不存在或者不可读</error>');
            exit;
        }
        // sql 文件的解析，剔除 use 语法
        $sql_content = static::parseFile($filepath);
        $output->writeln(sprintf('<info>%s</info>', $sql_content));
        $helper = $this->getHelper('question');
        $question = new ConfirmationQuestion('请检查以上导入的SQL是否正确,继续导入?[Y(default)/N]', TRUE);
        if (!$helper->ask($input, $output, $question)) {
            return;
        }
        // 导入SQL 到指定的数据
        $dbname = 'cmstop_schema';
        Schema::getDefaultConnection()->beginTransaction();
        $create_schema = sprintf('DROP DATABASE IF EXISTS `%s`;CREATE DATABASE `%s` DEFAULT CHARSET=\'utf8mb4\';USE `%s`;', $dbname, $dbname, $dbname);
        try {
            Schema::getDefaultConnection()->exec($create_schema);
            Schema::getDefaultConnection()->exec($sql_content);
            Schema::getDefaultConnection()->commit();
        } catch (\PDOException $exc) {
            Schema::getDefaultConnection()->rollBack();
            $output->writeln(sprintf('<error>%s</error>', $exc->getMessage()));
            exit;
        }
        $output->writeln('<info>导入数据库成功</info>');
    }

}
